﻿using System;
using System.ComponentModel;
using System.Linq.Expressions;
using System.Windows;
using System.Windows.Controls;

namespace TraceView.UI
{
    public class BaseHandlerView : UserControl, INotifyPropertyChanged
    {
        private TraceViewer _owner;

        public static readonly DependencyProperty DataTemplateProperty = DependencyProperty.Register("DataTemplate",typeof (DataTemplate),typeof (BaseHandlerView),new UIPropertyMetadata());
      
        public DataTemplate DataTemplate
        {
            get { return (DataTemplate) GetValue(DataTemplateProperty); }
            set { SetValue(DataTemplateProperty, value); }
        }

        public TraceViewer Owner
        {
            get { return _owner; }
            set
            {
                _owner = value;
                _owner.PropertyChanged += OwnerPropertyChanged;
            }
        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        protected void NotifyPropertyChanged<TProperty>(Expression<Func<TProperty>> property)
        {
            if (PropertyChanged == null)
                return;

            var lambda = (LambdaExpression)property;
            var unaryExpression = lambda.Body as UnaryExpression;
            MemberExpression memberExpression = unaryExpression != null
                                                    ? (MemberExpression)unaryExpression.Operand
                                                    : (MemberExpression)lambda.Body;
            PropertyChanged(this, new PropertyChangedEventArgs(memberExpression.Member.Name));
        }

        protected void SetProperty<TProperty>(Expression<Func<TProperty>> property, ref TProperty field, TProperty value)
        {
            field = value;
            NotifyPropertyChanged(property);
        }

        #endregion

        public virtual void SetDataTemplateForLevels(int level)
        {
        }
      
        private void OwnerPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "Level")
                SetDataTemplateForLevels(((TraceViewer) sender).Level);
        }
    }
}